﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace mogco
{
    public partial class ExtendedListView : UserControl
    {
        protected List<Button> ListViewButtons = new List<Button>();

        public ExtendedListView()
        {
            InitializeComponent();
        }

        public void AddButton(Button button, int row)
        {
            button.Tag = new int[] { row, 1 };
            this.ListViewButtons.Add(button);
        }

        private void SyncListViewButton()
        {
            if (this.listView1.Visible == true)
            {
                Rectangle _RowRect = new Rectangle(0, 0, 0, 0);
                Button _ListViewButton = null;

                //loop through each listview row
                for (int n = 0; n < this.listView1.Items.Count; n++)
                {
                    //get listview row rectangle
                    _RowRect = this.listView1.GetItemRect(n);

                    //get the corresponding button
                    _ListViewButton = this.ListViewButtons[n];

                    if (_RowRect.Top < _RowRect.Height)
                    {
                        //hide the button if it is going to overlap the column header
                        _ListViewButton.Visible = false;
                    }
                    else
                    {
                        //reposition the button
                        _ListViewButton.Left = _RowRect.Left + this.listView1.Columns[((int[])(_ListViewButton.Tag))[1] - 1].Width;
                        _ListViewButton.Top = _RowRect.Top;
                        _ListViewButton.Height = _RowRect.Height;
                        _ListViewButton.Width = this.listView1.Columns[((int[])_ListViewButton.Tag)[1]].Width;
                        _ListViewButton.Visible = true;
                    }
                }
            }
        }

        protected override void WndProc(ref Message m)
        {
            if (m.WParam.ToInt32() == this.Handle.ToInt32())
            {
                SyncListViewButton();
            }

            base.WndProc(ref m);
        }
    }
}
